package cn.yuanqiao.archive.liyong.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantRyMjDzb;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.liyong.domain.QueryParams;
import cn.yuanqiao.archive.liyong.domain.SeniorQuery;
import cn.yuanqiao.archive.liyong.mapper.ListQueryMapper;
import cn.yuanqiao.archive.liyong.service.ListQueryPageService;
import cn.yuanqiao.archive.liyong.service.ListQueryService;
import cn.yuanqiao.archive.liyong.service.SeniorQueryService;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 高级检索实现
 *
 * @ProjectName: JZSDAS
 * @Package: cn.yuanqiao.archive.liyong.service.impl
 * @ClassName: SeniorQueryServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2023/9/22 10:33
 * @Version: 1.0
 */
@Service
public class SeniorQueryServiceImpl implements SeniorQueryService {
    @Autowired
    ListQueryMapper listQueryMapper;

    @Autowired
    ListQueryService listQueryService;

    @Autowired
    ListQueryPageService listQueryPageService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    private static String dataBaseId;

    @Value("${FBswitch}")
    private boolean fbSwitch;

    @Autowired
    TenantMijiComparisonTableServiceImpl mijiComparisonTableService;


    @PostConstruct
    public void getDatabaseId() {
        dataBaseId = sqlSessionFactory.getConfiguration().getDatabaseId();
    }

    /**
     * 查询查询条件展示字段
     *
     * @param groupId 门类关联元数据方案id
     * @return
     */
    @Override
    public List<Map<String, Object>> queryApp(String groupId, String menuId, String qzh) {
        String tenantCode = SecurityUtils.getTenantCode();
        StringBuilder sql = new StringBuilder(" and t.IS_QUERY != 0  and t.TYPE in (0,1,3) ");
        List<Map<String, Object>> tabulationData = new ArrayList<>();
        if (StringUtils.isNotBlank(groupId)) {
            sql.append("  and t.GROUP_ID = '" + groupId + "' ");
        } else {
            List<Map<String, Object>> mapList = listQueryService.queryCategoryIds(null, menuId, qzh);
            if (ObjectUtils.isEmpty(mapList)) {
                return tabulationData;
            }
            String groupIds = mapList.stream().map(m -> m.get("GROUP_ID").toString()).collect(Collectors.joining(","));
            sql.append("  and t.GROUP_ID in (" + groupIds + ") ");
        }
        //查询元数据方案信息
        List<Map<String, Object>> dataList = listQueryMapper.selectLeftJoinTableData(" t.FIELD_CAPTION,t.FIELD_NAME,t.IS_QUERY,t.SHOWTYPE,t.TYPE ",
                sql.toString(), tenantCode + Constants.BIG_TABLE_M_DATA_LIST);
        tabulationData = dataList.stream().collect(Collectors.groupingBy(c -> c.get("FIELD_NAME"))).values().stream().map(a ->
        {
            Map<String, Object> mm = new HashMap<>();
            mm.put("FIELD_NAME", String.valueOf(a.get(0).get("FIELD_NAME")));
            mm.put("FIELD_CAPTION", a.stream().map(dd -> String.valueOf(dd.get("FIELD_CAPTION")).replaceAll(" ", "")).distinct().collect(Collectors.joining("/")));
            mm.put("SHOWTYPE", Integer.parseInt(a.get(0).get("SHOWTYPE").toString()));
            mm.put("TYPE", String.valueOf(a.get(0).get("TYPE")));
            return mm;
        }).collect(Collectors.toList());
        return tabulationData;
    }

    /**
     * 查询数据列表
     *
     * @param seniorQuery
     * @return
     */
    @Override
    public List<Map<String, Object>> seniorQuery(SeniorQuery seniorQuery) {
        String categoryId = seniorQuery.getCategoryId();
        String groupId = seniorQuery.getGroupId();
        String tenantCode = SecurityUtils.getTenantCode();
        StringBuilder query = new StringBuilder("");
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<Map<String, Object>> categoryList = new ArrayList<>();
        if (StringUtils.isNotBlank(categoryId) && StringUtils.isNotBlank(groupId)) {
            //查询门类信息
            categoryList = listQueryMapper.selectTableData(tenantCode + Constants.BIG_TABLE_NAME, "ITEM_TABLE_NAME," +
                    "FOLDER_TABLE_NAME,FILE_TABLE_NAME", " ID= " + categoryId);
        } else {
            categoryList = listQueryService.queryCategoryIds(null, seniorQuery.getMenuId(), seniorQuery.getQzh());
            if (ObjectUtils.isEmpty(categoryList)) {
                return new ArrayList<>();
            }
            groupId = categoryList.stream().map(m -> m.get("GROUP_ID").toString()).collect(Collectors.joining(","));
        }
        dataList = listQueryMapper.selectLeftJoinTableData(" t.FIELD_CAPTION,t.FIELD_NAME,t.IS_QUERY,t.SHOWTYPE,t.TYPE ",
                " and (t.IS_HIDDEN = 0 or t.FIELD_NAME in ('IS_ENTITY','GDCS_ID','CREATE_ID','EFILE_COUNT','MJ') ) and t.GROUP_ID in (" + groupId + ")", tenantCode + Constants.BIG_TABLE_M_DATA_LIST);
        //处理查询字段
        Map<String, String> map = listQueryService.initializationFiled(dataList);
        String unionSql = " UNION ALL ";
        StringBuilder sql = new StringBuilder("");
        //件
        sql.append("select DA_ID, SUB_TABLE_NAME," + map.get("file") + " from " +
                tenantCode + Constants.BIG_TABLE_YQDA + " where IS_DEL = 0 and STATE = '5' ");
        if (StringUtils.isNotBlank(map.get("folder"))) {
            //卷
            sql.append(unionSql);
            sql.append("select " + " FOLDER_ID as DA_ID , SUB_TABLE_NAME," + map.get("folder") + " from " +
                    tenantCode + Constants.BIG_TABLE_YQFOLDER + " where IS_DEL = 0 and STATE = '5' ");
        }
        if (StringUtils.isNotBlank(map.get("item"))) {
            sql.append(unionSql);
            //项目
            sql.append("select " + " ITEM_ID as DA_ID,  SUB_TABLE_NAME , " + map.get("item") + " from " +
                    tenantCode + Constants.BIG_TABLE_YQITEM + " where IS_DEL = 0 and STATE = '5' ");
        }
        //拼接查询条件
        query.append(queryTableNameSql(categoryList));
        query.append(concatQueryCondition(seniorQuery, " t."));
        PageUtils.startPage();
        String fieldl = map.get("filde") + " ,t.DA_ID,t.SUB_TABLE_NAME ";
        if (StringUtils.isBlank(seniorQuery.getOrder())) {
            String appData = listQueryMapper.selectAppData(tenantCode + "_TABLEHEAD ", "CONTENT", "  " +
                    "type= '-1' and menu_id= '" + seniorQuery.getMenuId() + "' and CATEGORY_ID= '" + categoryId + "' "+ " and QZH = '" +seniorQuery.getQzh()+ "' ");
            if (StringUtils.isNotBlank(appData)) {
                String[] split = appData.split(",");
                List<String> order = new ArrayList<>();
                for (String s : split) {
                    if (!s.contains(" NONE") && fieldl.contains(s.replace(" ASC", "").replaceAll(" DESC", ""))) {
                        order.add(s);
                    }
                }
                if (order != null && order.size() > 0) {
                    seniorQuery.setOrder(order.stream().collect(Collectors.joining(" NULLS LAST, ")) + " NULLS LAST ");
                }

            }
        }
        PageUtils.startPage();
        if (fbSwitch && (fieldl.contains(",MJ") || fieldl.contains("MJ,"))) {
            List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
            query.append(" and MJ in ('" + getdamjbyrymj.stream().map(m -> m.getDaMj()).collect(Collectors.joining("','")) + "') ");
        }
        List<Map<String, Object>> data = listQueryMapper.selectUnionALLTableDataPage(fieldl, sql.toString(), seniorQuery.getOrder(), query.toString());
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        List<Map<String, Object>> authority = listQueryPageService.authority(data, seniorQuery.getMenuId(), user, tenantCode);
        return authority;
    }

    public String queryTableNameSql(List<Map<String, Object>> categoryData) {
        StringBuilder query = new StringBuilder("");
        query.append(" and SUB_TABLE_NAME in ('");
        String fileName = categoryData.stream().map(m -> m.get("FILE_TABLE_NAME").toString()).collect(Collectors.joining("','"));
        String folderName = categoryData.stream()
                .filter(f -> f.get("FOLDER_TABLE_NAME") != null && !" ".equals(f.get("FOLDER_TABLE_NAME")))
                .map(m -> m.get("FOLDER_TABLE_NAME").toString()).collect(Collectors.joining("','"));
        String itemName = categoryData.stream()
                .filter(f -> f.get("ITEM_TABLE_NAME") != null && !" ".equals(f.get("ITEM_TABLE_NAME")))
                .map(m -> m.get("ITEM_TABLE_NAME").toString()).collect(Collectors.joining("','"));
        int i = 0;
        if (StringUtils.isNotBlank(fileName)) {
            i = 1;
            query.append(fileName);
        }
        if (StringUtils.isNotBlank(folderName)) {
            if (i == 1) {
                query.append("' ,'");
            }
            query.append(folderName);
        }
        if (StringUtils.isNotBlank(itemName)) {
            if (i == 1) {
                query.append("' ,'");
            }
            query.append(itemName);
        }
        query.append("' )");
        return query.toString();
    }


    /**
     * 处理前端查询条件
     *
     * @param listQuery
     * @param
     * @param t
     * @return
     */
    public String concatQueryCondition(SeniorQuery listQuery, String t) {
        StringBuilder queryCondition = new StringBuilder();
        //拼接前端查询条件
        if (listQuery.getQueryParams() != null && listQuery.getQueryParams().size() > 0) {
            List<QueryParams> queryParams = listQuery.getQueryParams();
            List<QueryParams> orList = queryParams.stream().filter(f -> f.getQueryType().equals("or")).collect(Collectors.toList());
            List<QueryParams> queryAnd = new ArrayList<>();
            if (orList != null && orList.size() > 0) {
                int j = 0;
                for (int i = 0; i < queryParams.size(); i++) {
                    QueryParams arams = queryParams.get(i);
                    if ("or".equals(arams.getQueryType())) {
                        QueryParams aor = queryParams.get(i);
                        String[] queryValue = new String[2];
                        queryValue[0] = aor.getValue();
                        if (j == 0) {
                            QueryParams aramss = queryParams.get(i - 1);
                            String[] queryValueOr = new String[2];
                            queryValueOr[0] = aramss.getValue();
                            String orsql = getQueryCriteriaByType(aramss.getColumn(), aramss.getShowType(), aramss.getQueryType(), queryValueOr);
                            orsql = orsql.replaceFirst("and", " ");
                            queryCondition.append(" and ( " + orsql);
                            j++;
                            queryAnd.remove(i - 1);
                        }
                        queryCondition.append(getQueryCriteriaByType(aor.getColumn(), aor.getShowType(), aor.getQueryType(), queryValue));
                    } else {
                        queryAnd.add(arams);
                    }
                }
                queryCondition.append(") ");
            } else {
                queryAnd.addAll(queryParams);
            }
            for (int i = 0; i < queryAnd.size(); i++) {
                QueryParams q = queryAnd.get(i);
                String[] queryValue = new String[2];    //查询值
                String queryType = q.getQueryType().equals("") ? " and " : q.getQueryType();      //查询类型
                String showType = q.getShowType();        //展示类型
                String fieldName = q.getColumn();
                queryValue[0] = q.getValue();        //根据查询项获取对应的查询值
                queryCondition.append(getQueryCriteriaByType(fieldName, showType, queryType, queryValue));
            }
        }
        return queryCondition.toString();
    }

    /**
     * <p>Title: getQueryCriteriaByType</p>
     * <p>Description: 根据传入的类型type 组合查询条件</p>
     *
     * @param column    列名
     * @param showType  查询类型
     *                  0	精确查询      = '匹配值';
     *                  1	模糊查询		like '%匹配值%'
     * @param queryType 布尔检索连接方式
     *                  and	与           '条件' and '条件';
     *                  or 或者		    '条件' or '条件';
     *                  not	不包含		'not '条件'
     * @param values    查询值
     * @return
     */
    public String getQueryCriteriaByType(String column, String showType, String queryType, String[] values) {
        String criteria = " ";
        Integer type = Integer.parseInt(showType);
        if (StringUtils.isBlank(values[0])) {
            values[0] = null;
        }
        switch (type) {
            case 0: //精确查询	= '匹配值';
                if ("not".equals(queryType)) {
                    criteria += " and IsNull(" + column + ",0) <> '" + values[0] + "' ";
                    break;
                }
                criteria += queryType + " " + column + " = '" + values[0] + "' ";
                break;
            case 1: //模糊查询	like '%匹配值%';
                if ("not".equals(queryType)) {
                    criteria += " and " + column + " != '" + values[0] + "' ";
                    break;
                }
                if (dataBaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())) {
                    criteria = " and regexp_match( CONCAT( " + column + " ) ,'(" + values[0] + ")') is not null ";
                } else {
                    criteria += queryType + "  regexp_like(" + column + ",'" + values[0] + "')>0 ";
                }
                break;
            default:
                break;
        }
        return criteria;
    }



}
